# -*- coding = utf-8 -*-
# @Time：2022/3/1 11:38
# @Author：3ic
# @File：detect_ub_frame.py
# @Software：PyCharm

import sys
import time

import win32api
import win32con
import win32process
import numpy as np
from PyQt5.QtWidgets import QApplication
import win32gui


def getCaptureScreen():
    hwnd = win32gui.FindWindow('LDPlayerMainFrame', '雷电模拟器')
    app = QApplication(sys.argv)
    screen = QApplication.primaryScreen()
    return hwnd, app, screen


def getOptionScreen(hwnd_, lparam):
    s = win32gui.GetWindowText(hwnd_)
    if len(s) > 3:
        global opthwnd
        opthwnd = hwnd_
        print("winfun, child_hwnd: %d   txt: %s" % (opthwnd, s))
    return 1


def setForegroundWindowByWin32GUI(hwnd):
    hForeWnd = win32gui.GetForegroundWindow()
    FormThreadID = win32api.GetCurrentThreadId()
    CWndThreadID = win32process.GetWindowThreadProcessId(hForeWnd)
    win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, True)
    win32gui.ShowWindow(hwnd, win32con.SW_SHOWNORMAL)
    win32gui.SetForegroundWindow(hwnd)
    win32process.AttachThreadInput(CWndThreadID[0], FormThreadID, False)


def fastCapture(screen, hwnd, x, y, w, h):
    img = screen.grabWindow(hwnd, x, y, w, h).toImage()
    ptr = img.constBits()
    ptr.setsize(img.byteCount())
    return np.array(ptr).reshape(img.height(), img.width(), 4)


def winPressKey(key, times=1, interval=0):
    key = ord(key)
    while times > 1:
        times -= 1
        win32gui.SendMessage(opthwnd, win32con.WM_KEYDOWN, key, 0)
        win32gui.SendMessage(opthwnd, win32con.WM_KEYUP, key, 0)
        time.sleep(interval)
    win32gui.SendMessage(opthwnd, win32con.WM_KEYDOWN, key, 0)
    win32gui.SendMessage(opthwnd, win32con.WM_KEYUP, key, 0)


def winClickMouse(x, y):
    client_pos = win32gui.ScreenToClient(opthwnd, (x, y))
    tmp = win32api.MAKELONG(client_pos[0], client_pos[1])
    win32gui.SendMessage(opthwnd, win32con.WM_ACTIVATE, win32con.WA_ACTIVE, 0)
    win32api.SendMessage(opthwnd, win32con.WM_LBUTTONDOWN, win32con.MK_LBUTTON, tmp)
    win32api.SendMessage(opthwnd, win32con.WM_LBUTTONUP, win32con.MK_LBUTTON, tmp)


def pressRole(key):
    win32gui.SendMessage(opthwnd, win32con.WM_KEYDOWN, 48+key, 0)
    pos_x = 340 + 221 * key  # 356
    while fastCapture(screen, hwnd, pos_x, 997, 1, 1)[0, 0, 0] > 100:
        time.sleep(0.003)
    win32gui.SendMessage(opthwnd, win32con.WM_KEYUP, 48+key, 0)


def setAccelerate(rate=1):
    img = fastCapture(screen, hwnd, 1706, 945, 10, 10)
    hash_val = np.sum(img[:, :, 2] > 127)
    if rate == 4:
        rate = 3
    elif rate != 2:
        rate = 1
    cur_rate = rate
    if hash_val == 100:
        cur_rate = 1
    elif hash_val == 0:
        cur_rate = 2
    elif hash_val == 70:
        cur_rate = 3
    press_times = (rate - cur_rate + 3) % 3
    if press_times > 0:
        winPressKey('X', press_times, 0.2)
        time.sleep(0.3)


detect_time = 73
dic_dt = [1, 4]
finish_time = detect_time - len(dic_dt) * 2 + 3


def executeTimeLine(sec, frame_cnt):
    if frame_cnt == 0 and sec == detect_time - dic_dt[0] * 2 + 2:
        pressRole(dic_dt[dic_dt[0]])
        dic_dt[0] += 1


def printSec(sec):
    if sec >= 60:
        sys.stdout.write('\n1:' + str(sec - 60).zfill(2))
    else:
        sys.stdout.write('\n0:' + str(sec).zfill(2))


def quitBattle():
    time.sleep(0.2)
    winClickMouse(1713, 82)
    time.sleep(0.8)
    winClickMouse(1200, 720)
    time.sleep(1.3)
    winClickMouse(1200, 720)
    time.sleep(0.2)


if __name__ == '__main__':
    hwnd, _, screen = getCaptureScreen()
    win32gui.EnumChildWindows(hwnd, getOptionScreen, None)

    setForegroundWindowByWin32GUI(hwnd)
    win32gui.SetWindowPos(hwnd, win32con.HWND_NOTOPMOST, 0, 0, 1920, 1030, win32con.SWP_SHOWWINDOW)

    sec = 90  # 轴的可用时间1
    last_digit = 1
    ten_sec = 9
    frame_cnt = 0
    cur_digit = last_digit

    time.sleep(0.1)
    winClickMouse(1600, 870)
    time.sleep(4)

    num_hash = {
        13157313: 0, 14335934: 1, 14473175: 2, 13091008: 3, 13421258: 4,
        14341072: 5, 14076361: 6, 14736604: 7, 13354179: 8, 13157314: 9,
        14340816: 5, 14010825: 6, 13354435: 8
    }

    isAccelerated = False

    while sec > finish_time:
        frame_cnt += 1
        img = fastCapture(screen, hwnd, 1595, 65, 8, 30)

        hash_val = (np.sum(img[:, :, 0] > 127) << 16) + \
                   (np.sum(img[:, :, 1] > 127) << 8) + \
                   (np.sum(img[:, :, 2] > 127))

        if sec - detect_time > 3:
            if not isAccelerated:
                winPressKey('X', 2, 0.2)
                isAccelerated = True
        elif isAccelerated:
            winPressKey('X')
            isAccelerated = False

        cur_digit = num_hash.get(hash_val, last_digit)
        if cur_digit != last_digit:
            if cur_digit == 9:
                ten_sec -= 1
            sec = ten_sec * 10 + cur_digit
            printSec(sec)
            sys.stdout.write('（' + str((frame_cnt - 85) * 60 // 85) + '）')
            frame_cnt = 0
            last_digit = cur_digit

        executeTimeLine(sec, frame_cnt)
        time.sleep(0.01)

    sys.stdout.write('\nFinish')
    setAccelerate(1)
    quitBattle()